import {LOCAL_PATH, PATH_VERSON, PROXY_URL} from '@/common/constant'
import {useEffect, useState} from 'react'
import {Upload} from 'antd'

export default props => {
  const {value, onChange} = props
  const [list, setList] = useState([]);

  useEffect(() => {
    value && setList([{ thumbUrl: PROXY_URL + value }])
    return () => undefined
  }, [value])

  const uploadImg = ({file,fileList}) => {
    setList(fileList);
    console.log(file, fileList);
    return file.status === 'done' && !file.response.err && onChange(file.response.data) 
  };

  const onPreview = async file => {
    let src = file.thumbUrl;
    if (!src) {
      src = await new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow.document.write(image.outerHTML);
  };

  return (
    <Upload
      action= {LOCAL_PATH + PATH_VERSON + '/uploadimg'}
      name="addimg"
      maxCount={1}
      listType="picture-card"
      fileList={list}
      onChange={uploadImg}
      onPreview={onPreview}
    >
      {list.length <1 && '+ Upload'}
    </Upload>
  )
}